/*
 * @Author: silence
 * @Date: 2023-07-05 11:14:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-01-04 11:00:29
 * @Description: 电站设置-顶部（是否卖电、工作模式）
 */
import 'package:ems_neutral_app/config/AppInfo.dart';
import 'package:ems_neutral_app/main.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/eventBus/eventBus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';

import '../../../common/widgets/cubitWidget/BottomSheetView.dart';
import '../../../utils/string/StringConstant.dart';
import '../Controller/PowerStationController.dart';
import 'PowerStationSetItem.dart';
import 'PsSetTimePeriodSettingView.dart';

class PsSetTopBgView extends StatefulWidget {
  const PsSetTopBgView({super.key});

  @override
  State<PsSetTopBgView> createState() => _PsSetTopBgViewState();
}

class _PsSetTopBgViewState extends State<PsSetTopBgView> {
  /// 是否卖电
  bool _isSellElectricity = true;

  /// 工作模式
  List _workingModeList = [];
  List _workingModeFuncDescList = []; // 工作模式功能描述
  int _workingModeIndex = 0;

  /// 是否显示自动卖电设置
  bool _isShowAutoSellElectricitySet = false;
  bool _autoSellElectricitySet = false;
  PowerStationController _powerStationController =
      Get.put(PowerStationController());

  // 充电设置
  List _powerSetList = [];
  List _powerSetDescList = [];
  int _powerSetIndex = 0;

  // 用电模式设置
  List _userPowerModeSetList = [];
  List _userPowerModeSetDescList = [];
  int _userPowerModeSetIndex = 1; //此索引是从1开始

  /// 是否自动充电
  bool _isAutoChargeSoc = true;

  @override
  void initState() {
    super.initState();
    _userPowerModeSetList = _powerStationController.getUsePowerModeList();

    _powerStationController.latestElectricityPriceMap.listen((p0) {
      loadData();
      if (this.mounted) setState(() {});
    });

    _powerStationController.powerStationSetInfo.listen((p0) {
      loadData();
      if (this.mounted) setState(() {});
    });
  }

  loadData() {
    /// 工作模式
    _workingModeIndex =
        _powerStationController.powerStationSetInfo['eybond_ctrl_112'];

    /// 是否卖电
    _isSellElectricity =
        _powerStationController.powerStationSetInfo['isPayPower'] == 1;

    /// 是否开启自动卖电
    _autoSellElectricitySet =
        _powerStationController.powerStationSetInfo['automaticSettings'] == 1;

    /// 充电设置
    _powerSetIndex = _powerStationController.powerStationSetInfo['powerSet'];

    /// 用电模式设置(因为此索引是从1开始，需要减去1)
    _userPowerModeSetIndex =
        _powerStationController.powerStationSetInfo['usePowerSet'] - 1;

    /// 处理是否显示自动卖电
    handleShowAutoSellElectricitySetView();

    /// 是否自动充电
    _isAutoChargeSoc =
        _powerStationController.powerStationSetInfo['isCheckSoc'] == 1;
  }

  /// 处理是否显示自动卖电
  handleShowAutoSellElectricitySetView() {
    Map latestElectricityPriceMap =
        _powerStationController.latestElectricityPriceMap;

    /// 当前是否是有电价数据
    List series = latestElectricityPriceMap['series'];
    _isShowAutoSellElectricitySet =
        (!SilTools.listIsEmpty(series)) ? true : false;

    if (_isShowAutoSellElectricitySet) {
      /// 当前是否是削峰填谷模式
      int workingModeIndex =
          _powerStationController.powerStationSetInfo['eybond_ctrl_112'];
      _isShowAutoSellElectricitySet = (workingModeIndex == 1);
    }

    if (this.mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    _powerSetList = [
      LangOf(context)?.power_setting?.gfyx,
      LangOf(context)?.power_setting?.gfsd,
    ];

    _powerSetDescList = [
      LangOf(context)?.power_setting?.power_set_desc_0,
      LangOf(context)?.power_setting?.power_set_desc_1,
    ];

    _workingModeList = [
      LangOf(context)?.power_setting?.zfzy,
      LangOf(context)?.power_setting?.xftg,
      LangOf(context)?.power_setting?.dcyx,
    ];

    _workingModeFuncDescList = [
      LangOf(context)?.power_setting?.zfzy_desc,
      LangOf(context)?.power_setting?.xftg_desc,
      LangOf(context)?.power_setting?.dcyx_desc,
    ];

    _userPowerModeSetDescList = [
      LangOf(context)?.power_setting?.sbu_desc,
      LangOf(context)?.power_setting?.sub_desc,
      LangOf(context)?.power_setting?.uti_desc,
      LangOf(context)?.power_setting?.sol_desc,
    ];

    /// 思道尔设备多一个并网优先
    if (_powerStationController.powerStationEntity.value.stationType == '3') {
      _workingModeList = [
        LangOf(context)?.power_setting?.zfzy,
        LangOf(context)?.power_setting?.xftg,
        LangOf(context)?.power_setting?.dcyx,
        LangOf(context)?.power_setting?.grid_priority,
      ];

      _workingModeFuncDescList = [
        LangOf(context)?.power_setting?.zfzy_desc,
        LangOf(context)?.power_setting?.xftg_desc,
        LangOf(context)?.power_setting?.dcyx_desc,
        LangOf(context)?.power_setting?.bwyx_desc,
      ];
    }
    return contentView();
  }

  contentView() {
    return Container(
      padding: EdgeInsets.only(top: 240.w),
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage(AppInfo.stationType == '3'
                ? 'imgs/set/set_bg_e3.png'
                : 'imgs/set/set_bg.png'),
            fit: BoxFit.fitWidth,
            alignment: Alignment.topCenter),
      ),
      child: Column(
        children: [
          /// 低压机型 显示充电设置
          if (_powerStationController.powerStationSetInfo['isH'] == false)
            chargingSettings(),

          /// 低压机型 显示用电模式设置
          if (_powerStationController.powerStationSetInfo['isH'] == false)
            userPowerModeSettings(),

          /// 高压机型 显示是否卖电
          if (_powerStationController.powerStationSetInfo['isH'])
            whetherToSellElectricity(),

          /// 高压机型 显示是否自动充电(思道尔机型除外)
          if (_powerStationController.powerStationSetInfo['isH'] &&
              _powerStationController.powerStationEntity.value.stationType !=
                  '3')
            whetherAutoChargeSoc(),

          /// 高压机型 显示工作模式
          if (_powerStationController.powerStationSetInfo['isH']) workingMode(),

          /// 自动卖电设置(削峰填谷 且 可以自动卖电)
          if (_isShowAutoSellElectricitySet) autoSellElectricitySet(),

          /// 充放电时间段设置(削峰填谷)
          if (_workingModeIndex == 1) PsSetTimePeriodSettingView(),
        ],
      ),
    );
  }

  /// 是否卖电
  whetherToSellElectricity() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.power_selling,
      leftImgPath: 'imgs/set/set_power_selling.png',
      rightView: Container(
        alignment: Alignment.centerRight,
        child: Switch(
            inactiveTrackColor: Colors.white,
            activeColor: ColorUtils.color_theme,
            thumbColor: MaterialStateProperty.resolveWith<Color>(
                (Set<MaterialState> states) {
              if (states.contains(MaterialState.disabled)) {
                return Colors.white.withOpacity(.48);
              }
              return Colors.white;
            }),
            value: _isSellElectricity,
            onChanged: showSellElectricityPromptPop),
      ),
      funcSubcribe: LangOf(context)?.power_setting?.power_selling_desc,
    );
  }

  /// 提示开启/关闭卖电提示
  showSellElectricityPromptPop(value) {
    String? popTitle = _isSellElectricity
        ? LangOf(context)?.power_setting?.is_turn_off_ps
        : LangOf(context)?.power_setting?.is_turn_on_ps;
    String? popContent = _isSellElectricity
        ? LangOf(context)?.power_setting?.turn_off_ps
        : LangOf(context)?.power_setting?.turn_on_ps;
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: popTitle,
            cancelButtonTitle: LangOf(context)?.common?.cancel,
            confrimButtonTitle: LangOf(context)?.common?.confirm,
            content: popContent), confrimFunc: () {
      /// 修改卖电设置
      _isSellElectricity = !_isSellElectricity;
      _powerStationController.powerStationSetInfo
          .update('isPayPower', (value) => _isSellElectricity ? 1 : 0);
    });
  }

  /// 是否自动充电
  whetherAutoChargeSoc() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.auto_battery,
      leftImgPath: 'imgs/set/set_battery.png',
      rightView: Container(
        alignment: Alignment.centerRight,
        child: Switch(
          inactiveTrackColor: Colors.white,
          activeColor: ColorUtils.color_theme,
          thumbColor: MaterialStateProperty.resolveWith<Color>(
              (Set<MaterialState> states) {
            if (states.contains(MaterialState.disabled)) {
              return Colors.white.withOpacity(.48);
            }
            return Colors.white;
          }),
          value: _isAutoChargeSoc,
          onChanged: (value) {
            /// 修改自动充电设置
            _isAutoChargeSoc = !_isAutoChargeSoc;
            _powerStationController.powerStationSetInfo
                .update('isCheckSoc', (value) => _isAutoChargeSoc ? 1 : 0);
            if (_isAutoChargeSoc) {
              showAutoChargeSocSetPromptPop();

              /// 自动充电时，工作模式变成电池优先
              _powerStationController.powerStationSetInfo
                  .update('eybond_ctrl_112', (value) => 2);
            }
          },
        ),
      ),
      funcSubcribe: LangOf(context)?.power_setting?.auto_battery_desc,
    );
  }

  /// 是否自动充电设置提示
  showAutoChargeSocSetPromptPop() {
    String? popTitle = LangOf(context)?.common?.configuration;
    String? popContent = LangOf(context)?.power_setting?.autoBattry;
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: popTitle,
            confrimButtonTitle: LangOf(context)?.common?.confirm,
            content: popContent),
        confrimFunc: () {});
  }

  /// 工作模式
  workingMode() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.work_pattern,
      leftImgPath: 'imgs/set/set_work_pattern.png',
      subTitle: _workingModeList[_workingModeIndex],
      tapRightViewFunc: showWorkingModePop,
      rightViewFlex: 2,
      funcSubcribe: _workingModeFuncDescList[_workingModeIndex],
    );
  }

  /// 显示工作模式选项
  showWorkingModePop() {
    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
          initialSelectedItem: _workingModeIndex,
          titles: _workingModeList.map<String>((e) => e).toList(),
          tapSureSeletedFunc: (selectedIndex) {
            /// 修改工作模式
            _workingModeIndex = selectedIndex;
            _powerStationController.powerStationSetInfo
                .update('eybond_ctrl_112', (value) => _workingModeIndex);

            /// 发送是否展示最新电价折线图
            bus.emit(StringConstant.OpenLatestElectricityPriceChart,
                [_workingModeIndex == 1]);

            /// 非削峰填谷模式，自动卖电改为关闭状态
            if (_workingModeIndex != 1) {
              _powerStationController.powerStationSetInfo
                  .update('automaticSettings', (value) => 0);
            }

            /// 非自动卖电模式，自动充电改为关闭状态
            if (_workingModeIndex != 2) {
              _powerStationController.powerStationSetInfo
                  .update('isCheckSoc', (value) => 0);
            }
          },
        ));
  }

  /// 自动卖电设置
  autoSellElectricitySet() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.auto_sell_set,
      leftImgPath: 'imgs/set/set_power_selling.png',
      rightView: Switch(
        inactiveTrackColor: Colors.white,
        activeColor: ColorUtils.color_theme,
        thumbColor: MaterialStateProperty.resolveWith<Color>(
            (Set<MaterialState> states) {
          if (states.contains(MaterialState.disabled)) {
            return Colors.white.withOpacity(.48);
          }
          return Colors.white;
        }),
        value: _autoSellElectricitySet,
        onChanged: (value) {
          /// 修改自动卖电设置
          _autoSellElectricitySet = !_autoSellElectricitySet;
          if (_autoSellElectricitySet) {
            showAutoSellElectricitySetPromptPop();
            // 自动卖电打开，获取智能卖电时间段
            _powerStationController.getAutoPeakLoadShifting(context);
          }
          _powerStationController.powerStationSetInfo.update(
              'automaticSettings', (value) => _autoSellElectricitySet ? 1 : 0);
        },
      ),
      funcSubcribe: LangOf(context)?.power_setting?.auto_sell_set_desc,
    );
  }

  /// 显示开启自动卖电设置提示
  showAutoSellElectricitySetPromptPop() {
    String? popTitle = LangOf(context)?.common?.configuration;
    String? popContent = LangOf(context)?.power_setting?.autoSetPrompt;
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: popTitle,
            confrimButtonTitle: LangOf(context)?.common?.confirm,
            content: popContent),
        confrimFunc: () {});
  }

  /// 充电设置
  chargingSettings() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.generation_setting,
      leftImgPath: 'imgs/set/set_charging_setting.png',
      subTitle: _powerSetList[_powerSetIndex],
      tapRightViewFunc: showChargingSettingsPop,
      rightViewFlex: 2,
      funcSubcribe: _powerSetDescList[_powerSetIndex],
    );
  }

  /// 显示充电设置选项
  showChargingSettingsPop() {
    SilBottomSheet.show(
      context: context,
      child: BottomSheetView(
        initialSelectedItem: _powerSetIndex,
        titles: _powerSetList.map<String>((e) => e).toList(),
        tapSureSeletedFunc: (selectedIndex) {
          /// 提示
          Future.delayed(Duration(milliseconds: 230)).then((value) {
            // 2O23年11月2日 去掉弹窗，改用副标题形式显示
            // showChargingSettingsPrompt(selectedIndex);

            /// 修改充电设置
            _powerSetIndex = selectedIndex;
            _powerStationController.powerStationSetInfo
                .update('powerSet', (value) => _powerSetIndex);
          });
        },
      ),
    );
  }

  /// 充电设置提示
  showChargingSettingsPrompt(int index) {
    BuildContext context = navigatorKey.currentState!.context;
    String? content = (index == 0)
        ? LangOf(context)?.power_setting?.power_set_desc_0
        : LangOf(context)?.power_setting?.power_set_desc_1;
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
          title: LangOf(context)?.common?.configuration,
          confrimButtonTitle: LangOf(context)?.common?.confirm, //'确认',
          content: content,
        ), confrimFunc: () async {
      /// 修改充电设置
      _powerSetIndex = index;
      _powerStationController.powerStationSetInfo
          .update('powerSet', (value) => _powerSetIndex);
    });
  }

  /// 用电模式设置
  userPowerModeSettings() {
    return PowerStationSetItem(
      title: LangOf(context)?.power_setting?.load_setting,
      leftImgPath: 'imgs/set/set_work_pattern.png',
      subTitle: _userPowerModeSetList[_userPowerModeSetIndex],
      tapRightViewFunc: userPowerModeSetPop,
      funcSubcribe: _userPowerModeSetDescList[_userPowerModeSetIndex],
    );
  }

  /// 显示用电模式设置选项
  userPowerModeSetPop() {
    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
          initialSelectedItem: _userPowerModeSetIndex,
          titles: _userPowerModeSetList.map<String>((e) => e).toList(),
          tapSureSeletedFunc: (selectedIndex) {
            /// 修改充电设置
            _userPowerModeSetIndex = selectedIndex;

            // 因为此索引是从1开始，保存时需要加上1
            _powerStationController.powerStationSetInfo
                .update('usePowerSet', (value) => _userPowerModeSetIndex + 1);
          },
        ));
  }
}
